from ij import IJ, WindowManager,ImagePlus,ImageStack 
from java.awt.event import MouseAdapter
from ij.gui import Roi,PolygonRoi

n=0
roiwidth=5
roilength=5
roiperimeter=4*(roilength+roiwidth)
store=[]

def doSomething(imp,canvas):
	global n
	global store
	global roiwidth
	global roilength
	global roiperimeter
	if n!=0:		
		oldbp = stack.getProcessor(n)
		for i in range(roiperimeter):
			oldbp.putPixel(store[i],store[i+roiperimeter],store[i+2*roiperimeter])			
	p = canvas.getCursorLoc()
	x = int(p.x)
	y = int(p.y)
	print x,' ',y  
	xarray=range(x-roiwidth,x+roiwidth)+[x+roiwidth for i in range(2*roilength)]+range(x+roiwidth,x-roiwidth,-1)+[x-roiwidth for i in range(2*roilength)]
	yarray=[y-roilength for i in range(2*roiwidth)]+range(y-roilength,y+roilength)+[y+roilength for i in range(2*roiwidth)]+range(y+roilength,y-roilength,-1)
	print xarray
	pixarray=[imp.getPixel(xarray[i],yarray[i])[0] for i in range(roiperimeter)] 
	store=xarray+yarray+pixarray
	ip = imp.getProcessor()
	roi = PolygonRoi([x-roiwidth,x+roiwidth,x+roiwidth,x-roiwidth], [y-roilength,y-roilength,y+roilength,y+roilength], 4, Roi.POLYGON)   
	ip.setValue(255)
	ip.draw(roi)
	n=imp.getCurrentSlice()
	
class ML(MouseAdapter):
	def mousePressed(self, event):
		canvas = event.getSource()
		imp = canvas.getImage()
		doSomething(imp,canvas)

imp = IJ.getImage() 
stack = imp.getImageStack()  
listener = ML()
IJ.runPlugIn("ij.plugin.Zoom","scale")
IJ.runPlugIn("ij.plugin.frame.ContrastAdjuster","")

for imp in map(WindowManager.getImage, WindowManager.getIDList()):
	win = imp.getWindow()
	if win is None:
		continue
	win.getCanvas().addMouseListener(listener)